// 中间地图数据
var url =
  "http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}";
var map = L.map("indexMap").setView([30, 104], 4);
L.tileLayer(url).addTo(map);

// 获取中心点
const getCenterPoint = (list) => {
  let latArr = [],
    lngArr = [],
    lat = 0,
    lng = 0;
  list.map((v) => {
    latArr.push(v[0]);
    lngArr.push(v[1]);
  });
  lat = (Math.min.apply(Math, latArr) + Math.max.apply(Math, latArr)) / 2;
  lng = (Math.min.apply(Math, lngArr) + Math.max.apply(Math, lngArr)) / 2;
  return [lng, lat];
};

var gzGeoJSON = null;

function initGeoJSON(options) {
  map.setView(options.centerLatlng, options.zoom);
  $.get(options.url, function (data) {
    var all = [
      // "#f7acbc",
      // "#deab8a",
      // "#817936",
      "#444693",
      // "#ef5b9c",
      // "#fedcbd",
    ];
    gzGeoJSON = L.geoJSON(data, {
      style: function () {
        return {
          color: "white",
          fillColor: all[Math.floor(Math.random() * all.length)],
          weight: 1,
          fillOpacity: 0.5,
        };
      },
      onEachFeature: function (feature, layer) {
        // console.log('feature--------------------------------------------', feature)
        // console.log('layer--------------', layer)
        if (feature.geometry.coordinates) {
          layer.center = getCenterPoint(feature.geometry.coordinates[0]);
        }
        if (feature.geometry.geometries) {
          console.log(
            JSON.stringify(feature.geometry.geometries[1].coordinates[0])
          );
          layer.center = getCenterPoint(
            feature.geometry.geometries[0].coordinates[0]
          );
        }
        // console.log(feature.id)
        layer.propertiesName = feature.id;
        // console.log('layer.propertiesName--------', layer.propertiesName)
        feature.properties &&
          feature.properties.name &&
          layer.bindTooltip(feature.properties.name, {
            direction: "bottom",
            className: "my_tooltip",
            permanent: true,
          });
      },
    })
      // 点击地图时执行
      .on("click", function (e) {
        // console.log('e.layer-----', e.layer.propertiesName)
        console.log("e--------", e);
        initGeoJSON({
          url: `./geojson/${e.layer.propertiesName}.json`, //番禺区各镇的经纬度数据
          centerLatlng: e.layer.center,
          zoom: 13,
        });
        gzGeoJSON.remove();
        var myDataObj = {
          shiJi: { name: "石碁镇", list: sJList },
          luoPu: { name: "洛浦街道", list: lPList },
          huaLong: { name: "化龙镇", list: hLList },
          nanCun: { name: "南村镇", list: nCList },
          xinZao: { name: "新造镇", list: xZList },
          daShi: { name: "大石街道", list: dSList },
          zhongCun: { name: "钟村街道", list: zCList },
          shiBi: { name: "石壁街道", list: sBList },
          dongHuan: { name: "东环街道", list: dHList },
          shaTou: { name: "沙头街道", list: sTList },
          qiaoNan: { name: "桥南街道", list: qNList },
          xiaoGuWei: { name: "小谷围街道", list: xGWList },
          daLong: { name: "大龙街道", list: dLList },
          shiLou: { name: "石楼镇", list: sLList },
          shiQiao: { name: "市桥街道", list: sQList },
          shaWan: { name: "沙湾街道", list: sWList },
        };
        // 如果是石碁镇就执行
        if (e.layer.propertiesName === "shiJi") {
          var villageList = sJList;
          document.getElementById("mySelect").style.display = "block"; //显示该镇下的各条村

          document.getElementById("first_level").style.display = "none";
          document.getElementById("rechargeAnswer").style.display = "none";
          document.getElementById("monitoring").style.display = "none";
          document.getElementById("first_level").style.display = "none";

          document.querySelector("#second_level #faultInfo").style.display =
            "none";
          document.getElementById("second_level").style.display = "block";
          document.getElementById("monitoringCount").style.display = "block";

          $("#cenTitleText").html("石基镇充电站分布图");
        }
        // 不是石碁镇就执行
        else {
          var villageList = myDataObj[e.layer.propertiesName].list;
          document.getElementById("mySelect").style.display = "block"; //显示该镇下的各条村
          $("#cenTitleText").html(
            `${myDataObj[e.layer.propertiesName].name}充电站分布图`
          );
        }
        // //拿到该镇下的各条村的名称数据
        function initSelect() {
          let mySelect = document.getElementById("mySelect"); //拿到地图上的下拉框
          // console.log(mySelect)
          if (villageList) {
            for (let index = 0; index < villageList.length; index++) {
              const element = villageList[index];
              let optionDom = document.createElement("option");
              optionDom.value = JSON.stringify(element);
              optionDom.innerHTML = element.name;
              mySelect.appendChild(optionDom);
            }
          }
        }
        initSelect();

        //选择该镇下的各条村时返回的数据
        var tempList = [];
        $("#mySelect").change(function (e) {
          // 移除所有marker
          if (markerList.length > 0) {
            markerList.map((v) => {
              v && v.remove();
            });
          }
          console.log("e----", e);
          let obj = JSON.parse(e.target.value);
          if (obj.name === "默认") return;
          tempList.push(obj);
          tempList.forEach((item) => {
            // console.log('obj-----', obj)
            if (obj.name !== item.name) {
              return false;
            } else {
              // console.log('obj---', obj)3
              tempList.push(obj);
              let latArr = [Number(item.latlng[1]), Number(item.latlng[0])];
              // console.log('latArr----', latArr)
              let icon = L.icon({
                iconUrl: "./images/ic_bike.png",
                iconSize: [40, 40],
              });
              var marker = L.marker(latArr, {
                draggable: false,
                icon: icon,
              }).addTo(map);
              // console.log('marker----', marker)

              marker.bindTooltip(item.name).openTooltip();
              markerList.push(marker);
              map.setView(latArr, 15);
            }
          });
        });
        // ----------
      })
      .addTo(map);
  });
}
initGeoJSON({
  url: "./geojson/py.json",
  centerLatlng: [22.97356659115516, 113.40156555175783],
  zoom: 10.5,
});
